package cn.usian.product.service.impl;

import cn.usian.jyzx.model.dto.h5.ProductSkuDto;
import cn.usian.jyzx.model.entity.product.Category;
import cn.usian.jyzx.model.entity.product.Product;
import cn.usian.jyzx.model.entity.product.ProductSku;
import cn.usian.jyzx.model.vo.common.Result;
import cn.usian.jyzx.model.vo.common.ResultCodeEnum;
import cn.usian.jyzx.model.vo.h5.IndexVo;
import cn.usian.product.mapper.ProductSkuMapper;
import cn.usian.product.service.CategoryService;
import cn.usian.product.service.ProductService;
import cn.usian.product.service.ProductSkuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, ProductSku> implements ProductSkuService {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ProductService productService;

    @Override
    public Result index() {
        /*
            需要从数据库中查询两部分信息,一部分是分类列表,另一部分是productSku列表,将两部分信息封装到IndexVo中,
            进一步将IndexVo封装到 result中并返回即可
         */
        List<ProductSku> list = list();
        //int i = 1/0;
        // 查询所有一级分类的信息,
        List<Category> categoryList = categoryService.queryLevelOne();

        return Result.build(IndexVo.builder().productSkuList(list).categoryList(categoryList).build(), ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result<PageInfo<ProductSku>> findByPage(Integer page, Integer pageSize,ProductSkuDto dto) {
        /*
            按条件分页查询
            准备一个分页对象和查询条件,然后调用mapper中的方法即可
         */
        //  按条件查询product对应的id
        List<Product> list = productService.findByPage(dto);
        List<Long> collect = list.stream().map(product -> product.getId()).collect(Collectors.toList());
        // 以 collect 中的数据和分页信息为前提,查询分页数据
        Page<ProductSku> page1 = new Page<>(page, pageSize);

        LambdaQueryWrapper<ProductSku> like = Wrappers.lambdaQuery(ProductSku.class)
                .in(collect.size()>0,ProductSku::getProductId, collect)
                .orderBy(dto.getOrder() == 1,false, ProductSku::getSaleNum)
                .orderBy(dto.getOrder() == 2,true, ProductSku::getSalePrice)
                .orderBy(dto.getOrder() == 3,false, ProductSku::getSalePrice);
        page(page1, like);
        PageInfo<ProductSku> info = new PageInfo<>(page1.getRecords());
        info.setTotal(page1.getTotal());
        info.setPageNum(page);
        info.setPageSize(pageSize);
        return Result.build(info, ResultCodeEnum.SUCCESS);
    }
}
